package mumu.android.lib.tool;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Toast;

public class Tools {

	/**
	 * 转换为int
	 * 
	 * @param str
	 * @return
	 */
	public static int toInt(Object obj) {
		try {
			String str = obj.toString();
			// 浮点型处理
			if (str.contains(".")) {
				if (str.indexOf(".") > 0)
					str = str.substring(0, str.indexOf("."));
			}
			int value = Integer.valueOf(str);

			return value;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static String toStr(Object str) {
		if (str == null || str.equals("null")) {
			return "";
		} else {
			String string = String.valueOf(str);
			string = string.trim();
			return string;
		}
	}

	public static String cutStr(Object str, Integer length) {
		if (str == null || str.equals("null")) {
			return "";
		} else {
			String string = String.valueOf(str);
			string = string.trim();
			if (string.length() <= length)
				return string;
			else {
				return string.substring(0, length - 1);
			}
		}
	}

	public static void toast(Context c, int srcId) {
		Toast.makeText(c, srcId, Toast.LENGTH_SHORT).show();
	}

	public static void toast(Context c, String str) {
		Toast.makeText(c, str, Toast.LENGTH_SHORT).show();
	}

	public static String getFileString(String path) {
		String str = path;

		File f = new File(str);
		if (f.exists()) {
			try {
				FileInputStream inStream = new FileInputStream(f);
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				int len = -1;
				byte[] buffer = new byte[1024];
				while ((len = inStream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, len);
				}

				byte[] data = outputStream.toByteArray();
				return new String(data, "utf-8");
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return "";
	}

	/** 取SD卡路径 **/
	public static String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory(); // 获取根目录
		}
		if (sdDir != null) {
			return sdDir.toString();
		} else {
			return "";
		}
	}

	/**
	 * 获取输入流
	 * 
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static InputStream GetInputStream(String str) throws UnsupportedEncodingException {
		return new ByteArrayInputStream(str.getBytes("utf-8"));
	}

	public static String StrToBase64(String strIn) {
		return Base64.encodeToString(strIn.getBytes(), Base64.DEFAULT).trim();
	}

	public static String Base64ToStr(String strIn) {
		byte b[] = android.util.Base64.decode(strIn, Base64.DEFAULT);
		return new String(b);
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dipToPx(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int pxToDip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static int getScreenWidth(Context context) {
		Resources res = context.getResources();
		DisplayMetrics metrics = res.getDisplayMetrics();
		return metrics.widthPixels;
	}

	public static int getScreenHeight(Context context) {
		Resources res = context.getResources();
		DisplayMetrics metrics = res.getDisplayMetrics();
		return metrics.heightPixels;
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {
		Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
				: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;

	}

	public static Drawable BitmapTodrawable(Bitmap bmp) {
		return new BitmapDrawable(bmp);
	}

	/**
	 * 安装文件
	 * 
	 * @param path
	 *            文件路径
	 * @param name
	 *            文件名称
	 * @param c
	 */
	public static void installApk(String path, String name, Context c) {
		File apkfile = new File(path, name);
		if (!apkfile.exists()) {
			return;
		}
		// 通过Intent安装APK文件
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		c.startActivity(i);
	}

	/**
	 * 获取软件版本号
	 * 
	 * @param context
	 * @return
	 */
	public static int getVersionCode(Context context) {
		int versionCode = 0;
		PackageManager pm = context.getPackageManager();
		PackageInfo pi;
		try {
			pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionCode = pi.versionCode;
		} catch (NameNotFoundException e1) {
			e1.printStackTrace();
		}
		return versionCode;
	}

	/**
	 * 获取软件版本号
	 * 
	 * @param context
	 * @return
	 */
	public static String getVersionName(Context context) {
		String versionName = "";
		PackageManager pm = context.getPackageManager();
		PackageInfo pi;
		try {
			pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
		} catch (NameNotFoundException e1) {
			e1.printStackTrace();
		}
		return versionName;
	}

	public static void mkdir(String dir) {
		File file = new File(dir);
		// 判断文件目录是否存在
		if (!file.exists()) {
			file.mkdir();
		}
	}

	/**
	 * 获取客户端ip地址
	 * 
	 * @return
	 */
	public static String getHostIp() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr.hasMoreElements();) {
					InetAddress inetAddress = ipAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress();
					}
				}
			}
		} catch (Exception e) {
		}
		return "";
	}

	/**
	 * 获取手机串号 需要权限 android.permission.READ_PHONE_STATE
	 * 
	 * @return
	 */
	public static String getPhoneIMEIorESN(Context c) {
		TelephonyManager telephonemanage = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
		try {
			return telephonemanage.getDeviceId();
		} catch (Exception e) {
		}
		return "";
	}

	/**
	 * 获取当前
	 */

	public static boolean getSystemService(Context context, String servicename) {
		ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> mserviceTasks = mActivityManager.getRunningTasks(100);
		for (RunningTaskInfo serinfo : mserviceTasks) {
			if (serinfo.baseActivity.getPackageName().equals(servicename)) {
				return true;
			}
		}
		return false;
	}

	public static boolean hasRecentTaskByPkg(Context context, String pkg) {
		ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> mserviceTasks = mActivityManager.getRunningTasks(100);
		for (RunningTaskInfo serinfo : mserviceTasks) {
			ComponentName cn = serinfo.topActivity;
			String pkgString = cn.getPackageName();
			if (pkgString.equals(pkg)) {
				return true;
			}
		}
		return false;
	}

	public static void Unzip(String zipFile, String targetDir) {
		int BUFFER = 4096; // 这里缓冲区我们使用4KB，
		String strEntry; // 保存每个zip的条目名称

		try {
			BufferedOutputStream dest = null; // 缓冲输出流
			FileInputStream fis = new FileInputStream(zipFile);
			ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
			ZipEntry entry; // 每个zip条目的实例

			while ((entry = zis.getNextEntry()) != null) {

				try {
					Log.i("Unzip: ", "=" + entry);
					int count;
					byte data[] = new byte[BUFFER];
					strEntry = entry.getName();

					File entryFile = new File(targetDir + strEntry);
					File entryDir = new File(entryFile.getParent());
					if (!entryDir.exists()) {
						entryDir.mkdirs();
					}

					FileOutputStream fos = new FileOutputStream(entryFile);
					dest = new BufferedOutputStream(fos, BUFFER);
					while ((count = zis.read(data, 0, BUFFER)) != -1) {
						dest.write(data, 0, count);
					}
					dest.flush();
					dest.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			zis.close();
		} catch (Exception cwj) {
			cwj.printStackTrace();
		}
	}

}
